package com.lhkj.ct.base.json.databind;

import com.baomidou.mybatisplus.annotation.IEnum;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;
import com.fasterxml.jackson.databind.node.JsonNodeType;
import com.lhkj.ct.base.utils.EnumUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.Serializable;

/**
 * 自定义枚举反序列化
 */
public class BaseEnumDeserializer extends JsonDeserializer<IEnum<?>> implements ContextualDeserializer {

    private static final Logger log = LoggerFactory.getLogger(BaseEnumDeserializer.class);

    private Class<? extends IEnum> clazz;

    public BaseEnumDeserializer() {
        log.info("Construct with no args");
    }

    public BaseEnumDeserializer(Class<IEnum> clazz) {
        this.clazz = clazz;
    }

    @SuppressWarnings("unchecked")
    @Override
    public IEnum<?> deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        JsonNode node = jp.getCodec().readTree(jp);
        Serializable asText = null;
        // string类型
        if(node.getNodeType() == JsonNodeType.STRING) {
            asText = node.asText();
            // int类型
        }else if(node.getNodeType() == JsonNodeType.NUMBER) {
            asText = node.asInt();
            // 对象类型
        }else{
            JsonNode code = node.get("code");
            if (code.getNodeType() == JsonNodeType.STRING) {
                asText = code.asText();
            }else if(code.getNodeType() == JsonNodeType.NUMBER) {
                asText = code.asInt();
            }
        }
        IEnum valueOf = null;
        if(asText != null && StringUtils.isNotBlank(asText.toString())){
            valueOf = EnumUtils.getByValue(asText, clazz);
        }
        return valueOf;
    }

    @SuppressWarnings({"unchecked"})
    @Override
    public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property) throws
            JsonMappingException {
        log.info("Construct with property class");
        return new BaseEnumDeserializer((Class<IEnum>) property.getType().getRawClass()); // 获取枚举字段的类型Class
    }


//    /**
//     * 枚举序列化
//     */
//    @Override
//    public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
//        if (object instanceof VEnum) {
//            VEnum<?,?> vEnum = (VEnum<?,?>) object;
//            serializer.write(vEnum.getValue());
//        } else {
//            serializer.out.writeEnum((Enum<?>) object);
//        }
//    }

}
